const fs = require("fs");
const path = require("path");

/* 按修改时间给文件夹内的视频文件排序 */
function listDirVideosByDateAsc(dirpath, callback) {
    // fs.readdir(dirpath, (err, items) => {
    //     // console.log(items);
    //     // console.log("----------");
    //     items = items
    //         .sort(
    //             (a, b) =>
    //                 fs.statSync(path.resolve(dirpath, a)).mtime -
    //                 fs.statSync(path.resolve(dirpath, b)).mtime
    //         )
    //         .filter((filename) => filename.endsWith(".wmv"));
    //     callback && callback(items);
    // });

    let items = fs.readdirSync(dirpath);

    items = items
        .sort(
            (a, b) =>
                fs.statSync(path.resolve(dirpath, a)).mtime -
                fs.statSync(path.resolve(dirpath, b)).mtime
        )
        .filter((filename) => filename.endsWith(".wmv"));

    callback && callback(items);
}

/* 获得格式化后的序号前缀 */
function formatIndexAdd0Prefix(index, len, sep = "_", lenAtLeastTwo = true) {
    index += "";
    len < 2 && lenAtLeastTwo ? (len = 2) : (len = len);
    while (index.length < len) {
        index = "0" + index;
    }
    return index + sep;
}

/* 生成新的文件名（去掉旧的序号前缀，添加新的序号前缀） */
function createNewNames(fnames = []) {
    return fnames.map((fname, index) => {
        // 去掉原来的序号
        let newname = fname.replace(/^\d+_?/, "");

        // 添加新的前缀
        newname =
            formatIndexAdd0Prefix(index + 1, (fnames.length + "").length) +
            newname;

        return [fname, newname];
    });
}

/* 按修改时间排序后，批量重命名视频文件 */
function renameDirVideosByDateAsc(dirpath, startFrom0 = false) {
    listDirVideosByDateAsc(dirpath, (fnames) => {
        const namePairs = createNewNames(fnames);
        // console.log(namePairs);
        namePairs.forEach((np) => {
            fs.renameSync(
                path.resolve(dirpath, np[0]),
                path.resolve(dirpath, np[1])
            );
        });
        console.log("DONE!", dirpath);
    });
}

/* 递归修改视频文件名，按照其在文件夹中的修改时间顺序，添加序号前缀 */
function rdvbdaInDirpath(dirpath) {
    const dirnames = fs.readdirSync(dirpath);
    dirnames.forEach((dirname) =>
        renameDirVideosByDateAsc(path.resolve(dirpath, dirname))
    );
}

/* 移除视频序号前缀 */
function removeVideoNumberPrefix(dirpath = __dirname) {
    files = fs.readdirSync(dirpath);
    // console.log(files);

    files.forEach((name) => {
        if (name.endsWith(".wmv")) {
            const newname = name.replace(/^\d+_?/, "");
            // console.log("name",name);
            // console.log("newname",newname);

            const oldpath = path.resolve(dirpath, name);
            const newpath = path.resolve(dirpath, newname);
            console.log(oldpath, newpath);

            fs.rename(
                oldpath,
                newpath,
                (err) => err && console.log("err=", err)
            );
        }
    });
}

/* 视频批量重命名 */
function main01() {
    // removeVideoNumberPrefix("D:\\给大头的视频\\项目视频\\JS商城")
    removeVideoNumberPrefix("D:\\给大头的视频\\项目视频\\弹幕");

    // listDirVideosByDateAsc(
    //     // "D:\\给大头的视频\\项目视频\\SASS",
    //     "D:\\给大头的视频\\项目视频\\Vue\\VUE基础",
    //     (items) => console.log(items)
    // );

    // renameDirVideosByDateAsc("D:\\给大头的视频\\项目视频\\React\\React项目实战");

    // rdvbdaInDirpath("D:\\给大头的视频\\项目视频");
    // rdvbdaInDirpath("D:\\给大头的视频\\项目视频\\Vue");
    // rdvbdaInDirpath("D:\\给大头的视频\\项目视频\\React");
}

/* 去除图片名称的多级后缀 */
function renameImgExtnames(dirpath) {
    // const reg = /![^\.]*\.webp/;
    const reg = /\.(jpg|png|gif|webp|svg)(.+)/;
    let items = fs.readdirSync(dirpath);
    items = items
        .sort(
            (a, b) =>
                fs.statSync(path.resolve(dirpath, a)).mtime -
                fs.statSync(path.resolve(dirpath, b)).mtime
        )
        .filter((filename) => reg.test(filename));
    // console.log(items);

    items.forEach((filename) => {
        const newname = filename.replace(reg, function (sub) {
            const tail = reg.exec(filename)[2];
            return sub.replace(tail, "");
        });
        fs.renameSync(
            path.join(dirpath, filename),
            path.join(dirpath, newname)
        );
    });
    console.log("rename done!");
}
// renameImgExtnames("D:\\GZH5\\H5-2111\\code\\W8_项目周\\mypro\\client\\assets");
// renameImgExtnames("D:\\GZH5\\ztest\\W7_前端工程化\\jdzb\\assets\\img");

function editFileUpdateImgExtnames(filepath) {
    const reg = /\.(jpg|png|gif|webp|svg)([^"'\)};]+)["']/g;
    const reg2 = /\.(jpg|png|gif|webp|svg)([^"'\)};]+)["']/;
    let content = fs.readFileSync(filepath).toString();

    content = content.replace(reg, function (sub) {
        const temp = reg2.exec(sub);
        console.log(sub, temp);

        const rabbish = temp[2];
        return sub.replace(rabbish, "");
    });

    fs.writeFileSync(filepath, content);
    console.log("job done");
}
// editFileUpdateImgExtnames("D:\\GZH5\\H5-2111\\code\\W8_项目周\\mypro\\client\\src\\views\\pages\\index.html")
editFileUpdateImgExtnames("D:\\GZH5\\ztest\\W7_前端工程化\\jdzb\\src\\views\\index.html")

function listDirFiles(dirpath) {
    const filenames = fs.readdirSync(dirpath);
    return filenames;
}
// console.log(listDirFiles("D:\\GZH5\\H5-2111\\wheels\\my_static_server\\public\\img"));

function editFileUpdateImgPath(dirpath, filepath) {
    const filenames = fs.readdirSync(dirpath);
    const newImgSrcs = {};
    filenames.forEach((fn) => {
        const key = fn.slice(0, fn.indexOf("."));
        const src = `http://localhost:8000/files/img/${fn}`;
        newImgSrcs[key] = src;
    });
    console.log(newImgSrcs);

    let content = fs.readFileSync(filepath).toString();
    for (let key in newImgSrcs) {
        const reg = new RegExp(`\.\./\.\./\.\./assets/${key}.(jpg|png)`)
        content = content.replace(reg, newImgSrcs[key]);
    }

    fs.writeFileSync(filepath, content);
    console.log("job done");
}
// editFileUpdateImgPath(
//     "D:\\GZH5\\H5-2111\\wheels\\my_static_server\\public\\img",
//     "D:\\GZH5\\H5-2111\\code\\W8_项目周\\mypro\\client\\src\\views\\pages\\index.html"
// );
